let db=require('../db/index.js')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const config = require('../config')

// 注册用户的处理函数
exports.regUser = (req, res) => {
	let userinfo =req.body

   const sql = `select * from ev_users where username=?`
   
	db.query(sql, [userinfo.username], function (err, results) {
		if(err){
			return res.cc(err)
		}
	if (results.length > 0) {
	return res.cc('用户名已经存在拉！')
	}
	
	userinfo.password = bcrypt.hashSync(userinfo.password, 10)
	
	const sql = 'insert into ev_users set ?'
	
	db.query(sql, { username: userinfo.username, password: userinfo.password },
	 function(err, results) {
		 if(err){
			 return res.cc(err)
		 }
	if (results.affectedRows !== 1) {
	return 
	res.cc('失败了')
	}else{
		return 	res.send({ status: 0, message: '注册成功！' })}
	})
	})
	
   // res.send('reguser OKa')
}
// 登录的处理函数
exports.login = (req, res) => {
	let userinfo=req.body
	let sql=`select * from ev_users where username=?`
   db.query(sql,userinfo.username,(err,results)=>{
	   if(err)return res.cc(err)
	   if(results.length!==1)return res.cc('登陆失败')
	   const compareResult = bcrypt.compareSync(userinfo.password, results[0].password)
	   if (!compareResult) {
	   return res.cc('登录失败！')
	   }
	   const user = { ...results[0], password: '', user_pic: '' }
	   const tokenStr = jwt.sign(user, config.jwtSecretKey, {
	   expiresIn: '10h', 
	   //有效时间是10个小时
	   })
	   res.send({
	   status: 0,
	   message: '登录成功！',
	   token: 'Bearer ' + tokenStr,
	   })
   })
  
// res.send('login OK')
}